package com.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.domain.User;
import com.util.JdbcUtils;

public class daoUser {

	/**
	 * 注册dao Integer>=1注册成功
	 * 
	 * @param myUser
	 * @return Integer>=1注册成功
	 */
	public Integer register(User myUser) {

		QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource()); // QueryRunner
																				// query和update方法
																				// CRUD

		String sql = "INSERT INTO user (username, password) VALUES (?, ?);"; // SQL语句

		// 执行SQL语句 update 执行 状态
		try {
			int update = queryRunner.update(sql, new Object[] { myUser.getUsername(), myUser.getPassword() });
			return update;
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
	}

	/**
	 * 查找一个用户是否存在  如果存在返回该对象  如果不存在返回null
	 * @param myUser
	 * @return  null OR User  Object
	 */
	public User selectUser(User myUser) {

		QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());// QueryRunner
																				// query和update方法
																				// CRUD
		//执行数据库查询
		String sql = "SELECT * FROM `user` WHERE `user`.username = ? AND `user`.`password` = ?";
		try {
			User query = queryRunner.query(sql, new BeanHandler<>(User.class),
					new Object[] { myUser.getUsername(), myUser.getPassword() });
			return query;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

}
